<template>
  <div>
    <Breadcrumb :opt-data="breadcrumbOptData"></Breadcrumb>
    <PageLayout>
      <div class="table-container height-100">
        <EZTable
          v-loading="tableLoading"
          :table-id="tableId"
          :table-hdl="tableHdl"
          :rows="genProtocolList"
          :custom-empty="true"
          @pageChanged="genProtocolData"
          @sizeChanged="genProtocolData"
          @filterChange="genProtocolData">
          <EmptyContent slot="empty" :opt-data="tableOptData"></EmptyContent>
        </EZTable>
      </div>
    </PageLayout>
    <el-dialog :title="formTitle" :visible.sync="showProtocolDialog" :close-on-click-modal="false" width="600px" center>
      <el-form :ref="protocolFormRef" :model="protocolForm" :rules="protocolFormRules"
               size="small" label-width="130px">
        <el-form-item label="协议名称" prop="protocolName">
          <el-input v-model="protocolForm.protocolName" placeholder="请填写协议名称"></el-input>
        </el-form-item>
        <el-form-item label="设备类别" prop="deviceType">
          <el-select v-model="protocolForm.deviceType" clearable filterable class="width-100"
                     placeholder="请选择设备类别">
            <el-option :label="deviceType.label" :value="deviceType.value" :key="idx"
                       v-for="(deviceType, idx) in deviceTypeData"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remarks">
          <el-input v-model="protocolForm.remarks" placeholder="请填写备注"></el-input>
        </el-form-item>
        <div class="text-align-right">
          <el-form-item>
            <el-button size="medium" @click="showProtocolDialog = false">取消</el-button>
            <el-button size="medium" type="primary" @click="submitProtocolForm">提交</el-button>
          </el-form-item>
        </div>
      </el-form>
    </el-dialog>
    <el-dialog
      title="通用协议小组件"
      :visible.sync="showProtocolWidgetDialog"
      :close-on-click-modal="false"
      width="1200px"
      center>
      <GeneralProtocolWidget  v-if="showProtocolWidgetDialog"  :genDeviceType="curGenDeviceType"  :protocolId="curProtocolId" :isProtocol="true"></GeneralProtocolWidget>
    </el-dialog>
  </div>
</template>

<script>
  import {msgCode} from "@/config/string";
  import {tableIdConfig, tableOptBtnConfig} from '@/config/table';
  import {routerMeta} from "@/router/routerMeta";
  import {confirmHandle, deepCopyWithJson, messageHandle, downloadExportData} from "@/utils";
  import {assembleTableOptBtn, getTableConfig, TableStateHdl} from "@/modules/routeParamStateHdl";
  import genProtocolTableCfg from "@/config/table/generalProtocols";
  import EZTable from '@/components/table/EZTable';
  import GeneralProtocolWidget from "@/page/relationData/generalProtocol/partial/GeneralProtocolWidget.vue";
  export default {
    name: "GeneralProtocol",
    components: { EZTable,GeneralProtocolWidget},
    data() {
      return {
        routerMeta: routerMeta,
        tableLoading: false,
        tableId: tableIdConfig.generalProtocol,
        tableHdl: null,
        genProtocolList: [],
        showProtocolDialog: false,
        isEditProtocol: false,
        protocolForm: {},
        protocolFormRules: {
          deviceType: [
            {required: true, message: '请选择设备类别', trigger: 'blur'}
          ],
          protocolName: [
            {required: true, message: '请填写协议名称', trigger: 'blur'}
          ],
        },
        protocolFormRef: 'protocolFormRef',
        deviceTypeData: [],
        showProtocolWidgetDialog:false,
        curProtocolId:'',
        curGenDeviceType:''
      }
    },
    computed: {
      formTitle() {
        return this.isEditProtocol ? '编辑通用协议' : '新增通用协议'
      },
      breadcrumbOptData() {
        return [
          {
            type: 'btn',
            label: '新增通用协议',
            icon: 'icon-tianjia',
            callback: () => {
              this.clickCreateBtn();
            }
          },
        ];
      },
      tableOptData() {
        return [
          {
            type: 'btn',
            label: '新增通用协议',
            icon: 'icon-tianjia',
            callback: () => {
              this.clickCreateBtn();
            }
          }
        ];
      },
    },
    activated() {
      this.initTableConfig();
      this.genProtocolData();
      this.getDeviceTypeData();
      this.initProtocolForm();
    },
    methods: {
      initProtocolForm() {
        this.protocolName = {
          deviceType: '',
          protocolName: '',
          remarks: "",
        };
      },
      resetComponentForm() {
        this.initProtocolForm();
        const protocolForm = this.$refs[this.protocolFormRef];
        protocolForm && protocolForm.resetFields();
      },
      initTableConfig() {
        if (this.tableHdl) return;
        const {columns = [], filters = []} = getTableConfig(this.tableId, genProtocolTableCfg);
        assembleTableOptBtn(columns, ({type = '', data = {}}) => {
          if (!type) return;
          const genProtocol = deepCopyWithJson(data);
          switch (type) {
            case tableOptBtnConfig.command.type:
              this.$router.push({
                name: routerMeta.generalProtocolCommand.name,
                params: {pid: genProtocol._id},
                query: {subTitle: genProtocol.protocolName, deviceType: genProtocol.deviceType}
              });
              break;
            case tableOptBtnConfig.delete.type:
              this.deleteGeneralProtocol(genProtocol);
              break;
            case tableOptBtnConfig.edit.type:
              const {
                _id, deviceType = '', protocolName = '', remarks = ''
              } = genProtocol;
              this.protocolForm = {
                _id: _id,
                deviceType: deviceType,
                protocolName: protocolName,
                remarks: remarks,
              };
              this.isEditProtocol = true
              this.showProtocolDialog = true;
              break;
            case tableOptBtnConfig.widgetList.type:
              this.showProtocolWidgetDialog= true;
              this.curGenDeviceType= genProtocol.deviceType;
              this.curProtocolId=genProtocol._id
              break;
            default:
              break;
          }
        });
        this.tableHdl = new TableStateHdl(this.$route.name, this.tableId, columns, filters);
      },
      clickCreateBtn() {
        this.resetComponentForm();
        this.showProtocolDialog = true
        this.isEditProtocol = false;
      },
      //通用协议列表
      genProtocolData() {
        this.tableLoading = true;
        const selector = {};
        const tableParam = this.tableHdl.assembleTableParam();
        API.generalProtocol.generalProtocolList({...tableParam, selector}).then(result => {
          this.tableLoading = false;
          const {data = [], total = 0} = result;
          const assembleCommandText = (src = []) =>
            src.map((s, index) => `${index + 1}:${s.methodAlias}`).join('<br>');
          this.genProtocolList = data.map(d => {
            return {
              ...d,
              methodName: assembleCommandText(d.generalCommands),
            }
          });

          this.tableHdl.total = total;
        }).catch(err => {
          console.log('err', err)
          this.tableLoading = false;
        });
      },
      //删除通用协议
      deleteGeneralProtocol(genProtocol = {}) {
        confirmHandle({label: `确定要删除通用协议：${genProtocol.protocolName} 吗?`}).then(() => {
          API.generalProtocol.generalProtocolDelete({_id: genProtocol._id}).then(result => {
            messageHandle({code: msgCode.DELETE_SUCCESS, title: '通用协议'});
            this.tableHdl.judgeTableMatched();
            this.genProtocolData();
          });
        }).catch(() => {
        });
      },
      //得到所有设备类别
      getDeviceTypeData() {
        API.deviceType.deviceTypeAll().then(result => {
          const {data = []} = result;
          this.deviceTypeData = data;
        }).catch(err => {
          console.log('err', err)
        });
      },
      //新增编辑通用协议
      submitProtocolForm() {
        this.$refs[this.protocolFormRef].validate((valid) => {
          if (!valid) return;
          this.tableLoading = true;
          if (this.isEditProtocol) {
            API.generalProtocol.generalProtocolEdit(this.protocolForm).then((resp) => {
              this.showProtocolDialog = false;
              this.$message({
                message: "通用协议编辑成功!",
                type: "success",
                duration: 1500,
              });
              this.genProtocolData();
              this.tableLoading = false;
            }).catch((err) => {
              console.log("err: ", err);
            });
          } else {
            API.generalProtocol.generalProtocolAdd(this.protocolForm).then((resp) => {
              this.showProtocolDialog = false;
              this.$message({
                message: "通用协议新增成功!",
                type: "success",
                duration: 1500,
              });
              this.genProtocolData();
              this.tableLoading = false;
            }).catch((err) => {
              console.log("err: ", err);
            });
          }
        })
      }
    },
  }
</script>
<style scoped lang="less">

</style>
